

package com.wctj.api.base.utils;

import org.springframework.core.NamedInheritableThreadLocal;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.Map;
import java.util.function.BiConsumer;

/**
 * 应用于 FeignClient传递请求头
 * @author carol
 */
public class FeignHeaderHelper {
    public static final String CUSTOMER_HEADER_PREFIX = "x-";
    public static final String HEADER_NAME_JWT = "Authorization";
    public static final ThreadLocal<Map<String, String>> HEADER_CONTEXT = new NamedInheritableThreadLocal("TMY Header Context");

    public FeignHeaderHelper() {
    }

    public static void parseContextHeaders(BiConsumer<String, String> consumer) {
        ServletRequestAttributes attributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
        if (attributes != null) {
            HttpServletRequest request = attributes.getRequest();
            Enumeration<String> headerNames = request.getHeaderNames();
            if (headerNames != null) {
                while(true) {
                    String name;
                    do {
                        if (!headerNames.hasMoreElements()) {
                            return;
                        }

                        name = ((String)headerNames.nextElement()).toLowerCase();
                    } while(!name.startsWith("x-") && !"Authorization".equalsIgnoreCase(name));

                    consumer.accept(name, request.getHeader(name));
                }
            }
        }
    }
}
